<template>
	<a-drawer :title="params.name" :width="500" :visible="visible"
		:footer-style="{ textAlign: 'right' }" @close="handleClose">
		<a-form :model="configForm" v-bind="formItemLayout">
			<a-form-item label="脚本名称" name="name">
				<span>{{scriptData?.title}}</span>
				<a-button @click="openScript" style="margin-left: 10px; border-radius: 5px;" size="small"
					type="primary">选择其他脚本</a-button>
			</a-form-item>
			<a-form-item label="音频配置" name="name">
				<span>{{scriptData?.audio_config?.name}}</span>
				<a-button style="margin-left: 10px;" type="link" @click="handleConfigAudio">编辑</a-button>
			</a-form-item>
			<a-form-item label="场景音频字幕" name="name">
				<a-radio-group @change="handleRadioChange" v-model:value="configForm.is_open" name="radioGroup">
					<a-radio value="on">开启</a-radio>
					<a-radio value="off">关闭</a-radio>
				</a-radio-group>
				<a-button style="margin-left: 10px;" type="link" @click="handleSubTitle">字幕效果</a-button>
			</a-form-item>
			<a-form-item label="字幕位置" name="name">
				<div class="media_con">
					<DraggableContainer class="drag_container" :referenceLineColor="'white'">
						<video v-if="videoObj.url && videoObj.type == 'video'" :src="videoObj.url"></video>
						<img v-if="videoObj.url && videoObj.type == 'image'" :src="videoObj.url" />
						<a-spin style="position: absolute; left: 80px; top: 140px;" :spinning="loading" />
						<!-- 移动容器 -->
						<Vue3DraggableResizable v-show="videoObj.word && configForm.is_open == 'on'"
							:initW="videoObj.width" :initH="videoObj.height"
							v-model:x="videoObj.elLeft" v-model:y="videoObj.elTop"
							v-model:w="videoObj.width" v-model:h="videoObj.height"
							v-model:active="videoObj.active" :draggable="true" :resizable="true" :parent="true" 
							@resize-end="handleResizeEnd" @drag-end="handleMoveEnd">
							<div :style="wordStyle">{{videoObj.word}}</div>
						</Vue3DraggableResizable>
					</DraggableContainer>
				</div>
			</a-form-item>
		</a-form>
		<chooseScript :visible="scriptVisible" @close="closeScript" />
		<subtitleSettings return_type="script" :visible="subTitleVisible" @close="closeSubTitle" />
		<!-- 音频配置 -->
		<AddDubbing :visible="visibleDubbing" @saveAudio="getAudioConfig" />
	</a-drawer>
</template>

<script>
	import {
		PlusOutlined
	} from '@ant-design/icons-vue';
	import {
		defineComponent,
		reactive,
		toRefs,
		ref,
		computed,
		watch,
		nextTick
	} from 'vue';
	import chooseScript from './chooseScript.vue';
	import subtitleSettings from './scriptSubtitle.vue';
	import AddDubbing from './AddDubbing.vue';
	
	import {
		DraggableContainer
	} from 'vue3-draggable-resizable';
	import Vue3DraggableResizable from 'vue3-draggable-resizable';
	//default styles
	import 'vue3-draggable-resizable/dist/Vue3DraggableResizable.css';
	
	import store from '@/store';
	export default defineComponent({
		props: {
			visible: {
				type: Boolean,
				default: false
			},
			params: {
				type: Object,
				default: () => {
					return {}
				}
			}
		},
		emits: ['close'],
		components: {
			chooseScript,
			subtitleSettings,
			AddDubbing,
			DraggableContainer,
			Vue3DraggableResizable
		},
		setup(props, context) {
			const state = reactive({
				scriptVisible: false,
				audioVisible: false,
				subTitleVisible: false,
				configForm: {
					is_open: 'on'
				},
				visibleDubbing: false,
				formItemLayout: {
					labelCol: {
						span: 6,
					},
					wrapperCol: {
						span: 14,
					},
				},
				loading: false
			})
			const handleClose = () => {
				context.emit('close')
			};
			const openScript = () => {
				state.scriptVisible = true
			}
			const closeScript = () => {
				state.scriptVisible = false
			}
			const handleConfigAudio = () => {
				state.visibleDubbing = true
			}
			const handleSubTitle = () => {
				if(state.configForm.is_open == 'off') return
				state.subTitleVisible = true
			}
			const closeSubTitle = () => {
				state.subTitleVisible = false
			}

			const getAudioConfig = (obj) => {
				state.visibleDubbing = false;
				if(obj){
					let name = obj?.audio?.name + '-' + obj?.audio?.human_style +
							'（' + obj?.audio?.emotion_style?.find(item => item.key == obj.emotion_category).value + '）'
					let audio_config = {
						speed: obj.speed,
						volume: obj.volume,
						voice_id: obj.audio.id,
						voice_type: obj.audio.timbre_id,
						gender_type: obj.audio.gender,
						emotion_category: obj.emotion_category,
						emotion_intensity: obj.emotion_intensity,
						emotion_style_key: obj.emotion_category,
						name: name
					}
					let params = {}
					Object.assign(params, scriptData.value)
					params.audio_config = audio_config
					store.dispatch('SetScriptData', params)
				}
			}
			
			const handleRadioChange = () => {
				let obj = {}
				Object.assign(obj, scriptData.value)
				obj.subtitle_status = state.configForm.is_open
				store.dispatch('SetScriptData', obj)
			}

			const videoObj = computed(() => {
				let resource_data = store.getters.clipJSON?.resource_data
				if (resource_data?.length && resource_data[0]?.video?.length) {
					let obj = resource_data[0]?.video[0]
					let wordObj = resource_data[0]?.items?.length?resource_data[0]?.items[0]:''
					return {
						url: obj.material_url,
						word: wordObj?.content,
						type: obj.material_type ? obj.material_type : obj.scene_type,
						width: 180,
						height: 30,
						elLeft: 0,
						elTop: 160,
						active: false,
					}
				} else {
					return {}
				}
			})
			
			const handleResizeEnd = (e) => {
				setPosition()
			}
			
			const handleMoveEnd = (e) => {
				setPosition()
			}
			
			const setPosition = () => {
				if(JSON.stringify(videoObj.value) == '{}') return
				nextTick(()=>{
					let params = {}
					let item = {}
					Object.assign(item, videoObj.value)
					Object.assign(params, store.getters.clipJSON?.script_data)
					params.subtitle_config['width'] = item.width
					params.subtitle_config['height'] = item.height
					params.subtitle_config['config']['x'] = Number(((item.elLeft + (item.width/2) - 90)/180).toFixed(3))
					params.subtitle_config['config']['y'] = Number(((160 - (item.elTop + (item.height/2)))/320).toFixed(3))
					store.dispatch('SetScriptData', params)
				})
			}
			
			const scriptData = computed(() => store.getters.clipJSON.script_data)
			
			watch(()=>store.getters.clipJSON?.script_data?.font, val=>{
				let subtitle_config =  scriptData.value?.subtitle_config
				if(subtitle_config.font && subtitle_config.material_url){
					state.loading = true
					customFont(subtitle_config.font, subtitle_config.material_url)
				}
			})
			
			watch(()=>scriptData.value?.subtitle_config, val=>{
				let subtitle_config =  scriptData.value.subtitle_config
				state.configForm.is_open = scriptData.value.subtitle_status
			}, {
				deep: true,
				immediate: true
			})
			
			const wordStyle = computed(() => {
				let subtitle_config =  scriptData.value.subtitle_config
				return {
					'overflow': 'hidden',
					'cursor': 'grab',
					'font-family': subtitle_config.font,
					'font-size': subtitle_config.font_size/2 + 'px',
					'width': '100%',
					'height': '100%',
					'color': subtitle_config.color,
					'background-color': subtitle_config.background,
					'display': 'flex',
					'align-items': subtitle_config.verticle_position == 'top' ? 'start' : subtitle_config
						.verticle_position == 'center' ? 'center' : 'end',
					'justify-content': subtitle_config.position == 'left' ? 'start' : subtitle_config.position ==
						'center' ? 'center' : 'end',
					'opacity': subtitle_config.opacity
				}
			})
			
			const customFont = (name, url) => {
				const fontFace = new FontFace(name, `url(${url})`);
				fontFace.load().then(() => {
					document.fonts.add(fontFace);
					state.loading = false
				}).catch((error) => {
					console.error(error);
					state.loading = false
				});
			}

			return {
				...toRefs(state),
				openScript,
				handleClose,
				closeScript,
				handleConfigAudio,
				handleSubTitle,
				closeSubTitle,
				videoObj,
				getAudioConfig,
				scriptData,
				handleRadioChange,
				wordStyle,
				handleResizeEnd,
				handleMoveEnd
			};
		}
	});
</script>

<style lang="less" scoped>
	.media_con {
		width: 180px;
		height: 320px;
		border-radius: 10px;
		background-color: #000;
		display: flex;
		align-items: center;
		justify-content: center;
		.drag_container{
			width: 180px;
			height: 320px;
			display: flex;
			align-items: center;
			justify-content: center;
			video {
				max-width: 100%;
				max-height: 100%;
			}
			
			img {
				max-width: 100%;
				max-height: 100%;
			}
		}
	}
</style>